// pages/login/login.js
import {
  loginSend,
  smsLogin,
  wxLogin,
  getUserInfo
} from "../../api/login";
import {
  updateInfo
} from "../../api/home";
const appData = getApp().globalData;
// const skinBehavior = require("../../utils/skinBehavior");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    phone: "",
    btnText: "获取验证码",
    canSend: true,
    canLogin: false,
    sms: "",
    isLoading: true,
    // background: '/images/home/bg.png'
    // myUserInfo: {},
  },
  // behaviors: [skinBehavior],
  /**
   * 生命周期函数--监听页面加载
   */
  sendMsm() {
    let phone = this.data.phone;
    var time = 120;
    var that = this;
    let reg = /^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$/;
    if (!phone) {
      wx.showToast({
        title: "手机号不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (!reg.test(phone)) {
      wx.showToast({
        title: "手机号码格式不正确",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    console.log("点击验证码", this.data.phone);
    let obj = {
      phone: this.data.phone,
    };
    loginSend(obj)
      .then((res) => {
        console.log("res: ", res);
        if (res.success) {
          wx.showToast({
            title: "验证码发送成功",
            icon: "none",
            duration: 2000,
          });
          var timers = setInterval(function () {
            time--;
            if (time > 0) {
              that.setData({
                btnText: time,
                canSend: false,
              });
            } else {
              that.setData({
                btnText: "获取验证码",
                canSend: true,
              });
              clearInterval(timers);
            }
          }, 1000);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        }
      })
      .catch((err) => {
        // console.log("err: ", err);
      });
  },
  codeInput(e) {
    if (e.detail.length === 6) {
      this.setData({
        canLogin: true,
      });
    } else {
      this.setData({
        canLogin: false,
      });
    }
  },
  login() {
    let phone = this.data.phone;
    let reg = /^[1][1,2,3,4,5,6,7,8,9][0-9]{9}$/;
    if (!phone) {
      wx.showToast({
        title: "手机号不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (!reg.test(phone)) {
      wx.showToast({
        title: "手机号码格式不正确",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    let obj = {
      phone: this.data.phone,
      clientId: 0,
      code: this.data.sms,
      random: 0,
    };
    smsLogin(obj)
      .then((res) => {
        console.log("res: ", res);
        if (res.success) {
          var obj = res.data;
          wx.setStorage({
            key: "token",
            data: obj.access_token,
          });
          wx.setStorage({
            key: "tokenData",
            data: JSON.stringify(obj),
          });
          // wx.switchTab({
          //   url: "/pages/home/home",
          // });
          setTimeout(() => {
            this.updateInfo();
          }, 50);

          // wx.switchTab({
          //   url: "/pages/home/home",
          // });
        }
      })
      .catch((err) => {});
  },
  getPhoneNumber(e) {
    if (!e.detail.code) return;
    console.log(e.detail.code);
    let obj = {
      code: e.detail.code,
    };
    wxLogin(obj)
      .then((res) => {
        console.log("res: ", res);
        if (res.success) {
          var obj = res.data;
          wx.setStorage({
            key: "token",
            data: obj.access_token,
          });
          wx.setStorage({
            key: "tokenData",
            data: JSON.stringify(obj),
          });
          setTimeout(() => {
            this.updateInfo();
          }, 50);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000,
          });
        }
      })
      .catch((err) => {
        wx.showToast({
          title: err.msg,
          icon: "none",
          duration: 2000,
        });
        console.log("err: ", err);
      });
  },
  updateInfo() {
    // console.log("appData.userInfo.avatarUrl", appData.userInfo.avatarUrl);
    if (appData.userInfo && appData.userInfo.avatarUrl) {
      let obj = {
        photoFileName: appData.userInfo.avatarUrl,
      };
      updateInfo(obj)
        .then((res) => {
          console.log("更新头像res: ", res);
          this.getUserInfo()
        })
        .catch((err) => {
          console.log("err: ", err);
        });
    } else {
      this.getUserInfo()
    }

  },
  getUserInfo() {
    getUserInfo()
      .then((res) => {
        console.log("获取用户信息并且存储res: ", res);
        if (res.success) {
          // 把用户信息存在store
          appData.myUserInfo = res.data;
          appData.userAvatarUrl = res.data.photoFileName;
          // this.setData({
          //   myUserInfo: res.data,
          // });
          // 把用户信息存在缓存
          var obj = JSON.stringify(res.data);
          wx.setStorage({
            key: "USER_INFO",
            data: obj,
          });
          wx.reLaunch({
            url: "/pages/loading/loading",
          });
          // wx.reLaunch({
          //   url: "/pages/home/home",
          // });
          // wx.switchTab({
          //   url: "/pages/home/home",
          // });
          // wx.getSetting({
          //   success: (res) => {
          //     console.log("getSetting-res: ", res);
          //     if (res.authSetting["scope.userInfo"]) {
          //       // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          //       wx.getUserInfo({
          //         success: (res) => {
          //           console.log("res--获取头像: ", res);
          //           // 可以将 res 发送给后台解码出 unionId
          //           app.globalData.userInfo = res.userInfo;
          //           // this.globalData.userInfo = res.userInfo;
          //           // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          //           // 所以此处加入 callback 以防止这种情况
          //           if (this.userInfoReadyCallback) {
          //             this.userInfoReadyCallback(res);
          //           }
          //         },
          //       });
          //     }
          //   },
          // });
        }
      })
      .catch((err) => {});
  },
  onLoad(options) {
    let that = this
    setTimeout(() => {
      that.setData({
        isLoading: false
      })
    }, 500);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});